import { fetchDict } from '@/redux/dict/dict-api';
import {
  Button,
  Col,
  Form,
  Image,
  Row,
  Space,
  Upload,
} from '@douyinfe/semi-ui';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { IconPlus } from '@douyinfe/semi-icons';
import { useNavigate } from 'react-router-dom';
import { getItemIcon, uploadFile } from '@/redux/application/application-api';
import { blobToBase64 } from '@/utils/img-handle';

const ApplicationEdit = ({
  entity,
  persistEntity,
  formApiRef,
}: {
  entity?: any;
  persistEntity?: (entity: any) => void;
  formApiRef?: (value: any) => void;
}) => {
  const {
    Section,
    Input,
    InputNumber,
    AutoComplete,
    Select,
    TreeSelect,
    Cascader,
    DatePicker,
    TimePicker,
    TextArea,
    CheckboxGroup,
    Checkbox,
    RadioGroup,
    Radio,
    Slider,
    Rating,
    Switch,
    TagInput,
  } = Form;
  const navigate = useNavigate();
  const dispatch = useDispatch<any>();
  // 应用类型选项
  const [appTypeOptions, setAppTypeOptions] = useState<any[]>([]);
  // 授权类型选项
  const [grantTypeOptions, setGrantTypeOptions] = useState<any[]>([]);
  // 托管类型选项
  const [managedTypeOptions, setManagedTypeOptions] = useState<any[]>([]);
  // 文件
  const [fileList, setFileList] = useState<any[]>([]);
  const [initialIcon, setInitialIcon] = useState<any>(null);
  // const uploadRef = useRef<any>();
  const uploadRef = React.createRef<any>();
  const message = '该项为必填项';
  useEffect(() => {
    return () => {};
  }, []);

  useEffect(() => {
    Promise.all([
      fetchDict({
        pageNum: 1,
        pageSize: 100,
        dictType: 'app',
      }),
      fetchDict({
        pageNum: 1,
        pageSize: 100,
        dictType: 'system_oauth2_grant_type',
      }),
      fetchDict({
        pageNum: 1,
        pageSize: 100,
        dictType: 'app_managed_type',
      }),
    ]).then(([types, grantTypes, managedType]) => {
      setAppTypeOptions(types?.data?.data?.list);
      setGrantTypeOptions(grantTypes?.data?.data?.list);
      setManagedTypeOptions(managedType?.data?.data?.list);
    });
  }, []);

  const initialValue = useMemo(() => {
    let tempValues = { ...entity };
    if (!tempValues?.id) {
      tempValues.status = 0;
    }
    if (tempValues.icon) {
      getItemIcon(tempValues.icon).then((result: any) => {
        if (result.data) {
          blobToBase64(result.data, (dataUrl: any) => {
            setInitialIcon(dataUrl);
          });
        }
      });
    }
    if (tempValues.categoryId) {
      tempValues.categoryId = tempValues.categoryId.toString();
    }
    if (tempValues.appManagedType) {
      tempValues.appManagedType = tempValues.appManagedType.toString();
    }
    return tempValues;
  }, [entity]);

  return (
    <Form
      labelPosition='left'
      labelAlign='right'
      labelWidth={'180px'}
      getFormApi={(api: any) => formApiRef && formApiRef(api)}
      // validateFields={() => ''}
      layout='horizontal'
      onSubmit={(values: any) => {
        let submitValue = { ...values };
        if (fileList.length > 0) {
          submitValue.icon = fileList[0]?.name;
        }
        console.log('提交数据--->', submitValue);
        persistEntity && persistEntity(submitValue);
      }}
      initValues={initialValue}
      // onReset={() => applyFilter(initialFilter)}
    >
      <div className='grid grid-cols-1 gap-4 w-full'>
        <Input
          field='clientId'
          label='客户端编号'
          trigger='blur'
          rules={[{ required: true, message }]}
        />
        <Input
          field='secret'
          label='客户端秘钥'
          trigger='blur'
          rules={[{ required: true, message }]}
        />
        <Input
          field='title'
          label='应用名称'
          trigger='blur'
          rules={[{ required: true, message }]}
        />
        <div className='flex'>
          <div
            className='font-semibold text-right'
            style={{
              width: '180px',
              paddingRight: '16px',
              boxSizing: 'border-box',
            }}
          >
            应用图标
          </div>
          {initialIcon && fileList.length === 0 && (
            <div
              className='mr-2'
              onClick={() => {
                console.log('重新上传--->', uploadRef);
                uploadRef.current?.openFileDialog();
              }}
            >
              <Image src={initialIcon} width={96} height={96} preview={false} />
            </div>
          )}
          {/* {!initialIcon && fileList.length === 0 && ( */}
          <Upload
            // field='icon'
            // label='应用图标'
            className={`${!initialIcon ? 'visible' : 'invisible'}`}
            limit={1}
            action=''
            fileList={fileList}
            withCredentials
            ref={uploadRef}
            customRequest={({ file }) => {
              new Promise((resolve, reject) => {
                const filesData = new FormData();
                filesData.append('file', file.fileInstance!);
                uploadFile(filesData)
                  .then((res: any) => {
                    if (res.data.data) {
                      resolve(res.data.data);
                      setInitialIcon(null);
                      setFileList([
                        {
                          fileInstance: file.fileInstance,
                          name: res.data.data,
                          status: 'success',
                          size: file.size,
                          uid: file.uid,
                          url: file.url,
                        },
                      ]);
                    }

                    if (!res.data.data) {
                      reject(false);
                    }
                  })
                  .catch(() => reject(false));
              });
            }}
            onRemove={(e: any) => {
              setFileList(fileList.filter((file) => file.uid !== e.uid));
            }}
            listType='picture'
            accept='image/*'
          >
            <IconPlus size='extra-large' />
          </Upload>
          {/* )} */}
        </div>

        <TextArea
          style={{ height: 120 }}
          field='description'
          label='应用描述'
          placeholder='请填写应用描述'
        />
        <Select
          style={{ width: '100%' }}
          field='categoryId'
          label='应用类型'
          placeholder='请选择你的应用类型'
          rules={[{ required: true, message }]}
          onChange={(e) => {
            console.log('更改--->', e);
          }}
        >
          {appTypeOptions?.map((type: any, idx: any) => (
            <Select.Option key={`type_${idx}`} value={type?.value}>
              {type?.label}
            </Select.Option>
          ))}
        </Select>
        <RadioGroup
          field='status'
          label='状态'
          rules={[{ type: 'number' }, { required: true, message }]}
        >
          <Radio value={0}>开启</Radio>
          <Radio value={1}>关闭</Radio>
        </RadioGroup>
        <TagInput
          field='redirectUris'
          label='可重定向的URL地址'
          placeholder='请输入重定向地址，可多填，以enter键分隔'
          rules={[{ required: true, message }]}
        />
        <InputNumber
          field='accessTokenValiditySeconds'
          label='访问令牌的有效期'
          rules={[{ required: true, message }]}
        />
        <InputNumber
          field='refreshTokenValiditySeconds'
          label='申请令牌的有效期'
          rules={[{ required: true, message }]}
        />
        <Select
          multiple
          style={{ width: '100%' }}
          field='authorizedGrantTypes'
          label='授权类型'
          placeholder='请选择你的授权类型'
          rules={[{ required: true, message }]}
        >
          {grantTypeOptions?.map((type: any, idx: any) => (
            <Select.Option key={`grant_type_${idx}`} value={type?.value}>
              {type?.label}
            </Select.Option>
          ))}
        </Select>
        <Select
          style={{ width: '100%' }}
          field='appManagedType'
          label='托管类型'
          placeholder='请选择你的托管类型'
          rules={[{ required: true, message }]}
        >
          {managedTypeOptions?.map((type: any, idx: any) => (
            <Select.Option key={`type_${idx}`} value={type?.value}>
              {type?.label}
            </Select.Option>
          ))}
        </Select>
      </div>
      <div className='w-full flex justify-end items-center py-4 '>
        <Button onClick={() => navigate(-1)}>取消</Button>
        <Button theme='solid' htmlType='submit' className='mx-2'>
          保存
        </Button>
      </div>
    </Form>
  );
};

export default ApplicationEdit;
